package com.wangzh.concurrent.lock.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

public class Demo {

    static Long min =1L;
    static Long max =10_0000_0000L;
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        test1();
        test2();
        test3();
    }

    public static void test1(){
        long start = System.currentTimeMillis();
        long sum =0;
        for (long i = 1L; i <= max; i++) {
            sum+=i;
        }
        long end = System.currentTimeMillis();
        System.out.println(end-start);
        System.out.println(sum);
    }
    public static void test2() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();

        ForkJoinPool forkJoinPool = new ForkJoinPool();
        MyForkJoin myForkJoin = new MyForkJoin(min, max);
        ForkJoinTask<Long> submit = forkJoinPool.submit(myForkJoin);
//        Long rawResult = myForkJoin.getRawResult();
        Long l = submit.get();
        long end = System.currentTimeMillis();

        System.out.println(end-start);
        System.out.println(l);
    }

    public static void test3() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();

        long reduce = LongStream.rangeClosed(min, max).parallel().reduce(1, Long::sum);
        long end = System.currentTimeMillis();

        System.out.println(end-start);
        System.out.println(reduce);
    }
}
